import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store/index.js'

const API_URL = process.env.NODE_ENV === 'development' ? '' : process.env.VUE_APP_API_URL

// 这个方法是防止在一定时间内多个接口报同一个错误
const messageMap = {}
function showMessage (code, message) {
  if (messageMap[code] === undefined) {
    ElMessage({ type: 'error', message })
  } else {
    clearTimeout(messageMap[code])
  }
  messageMap[code] = setTimeout(() => {
    clearTimeout(messageMap[code])
    delete messageMap[code]
  }, 2000)
}

const request = axios.create()

// 超时时间20秒
request.defaults.timeout = 30 * 1000

// 请求拦截
request.interceptors.request.use(
  (config) => {
    // 加token
    config.headers.AccessToken = store.state.userInfo?.accessToken
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 响应拦截
request.interceptors.response.use(
  (config = {}) => {
    const data = config.data?.code || ''
    switch (data) {
      case '401':
      case '403':
        // 用户登录状态出现问题
        showMessage(config.data.code, config.data.message)
        break
      case '20080002':
        // 用户无数据权限
        showMessage(config.data.code, config.data.message)
        break
      case '0001':
        // 系统错误
        showMessage(config.data.code, config.data.message)
        break
    }
    return config.data || {}
  },
  (err) => {
    const data = err?.response?.data || {}
    if (data.code) {
      showMessage(data.code, data.message)
    } else {
      switch (data.code) {
        // 系统在维护中，跳转提示页面
        case 500:
        case 404:
          showMessage(data.code, data.message)
          break
        case 504:
          showMessage(data.code, '网站正在维护，请稍后再试！')
          break
        default:

          showMessage('err', '网络错误')
      }
    }
    return Promise.reject(err)
  }
)

export {
  request,
  API_URL
}
